package com.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpUtils {

	private HttpUtils() {
		
	}
	
	private static final HttpUtils httpUtil = new HttpUtils();
	
	public static HttpUtils getInstance(){
		return httpUtil;
	}
	
	public String httpGet(HashMap<String, String> params, String urlStr){
		StringBuffer result = new StringBuffer();
		BufferedReader reader = null;
		try {
			URL url = new URL(getUrl(params, urlStr));
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(120000);
            connection.setReadTimeout(120000);
            connection.connect();
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
        finally {
            try {
                if (reader != null) {
                	reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		return result.toString();
	}
	
	public String httpPost(String urlStr, HashMap<String, String> params){
		StringBuffer sb = new StringBuffer();
		try {
            //创建连接
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(120000);
            connection.setReadTimeout(120000);
            // head
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            connection.connect();
            //POST请求
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());
            out.write(getBodyParams(params).getBytes("utf-8")); // 需指定编码格式，否则中文无法发送
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
		return sb.toString();
	}
	
	/**
	 * 拼接POST请求参数
	 * @param params
	 * @return
	 */
	private String getBodyParams(HashMap<String, String> params) {
		StringBuffer sb = new StringBuffer();
		// 添加url参数
		if (params != null && params.size() > 0) {
			try {
				Iterator<Entry<String, String>> entryKeyIterator  = params.entrySet().iterator();
				while (entryKeyIterator.hasNext()) {
					Entry<String, String> entry = entryKeyIterator.next();
					String key = entry.getKey();
					String value = entry.getValue();
					sb.append(URLEncoder.encode(key, "UTF-8"));
					sb.append("=");
					sb.append(URLEncoder.encode(value, "UTF-8"));
					sb.append("&");
				}
				int position = sb.lastIndexOf("&");
				sb.replace(position, position + 1, "");
			} catch (Exception e) {
				return sb.toString();
			}
		}
		return sb.toString();
	}
	
	/**
	 * 拼接GET请求参数
	 * @param params
	 * @param url
	 * @return
	 */
	private String getUrl(Map<String, String> params, String url) {
		// 添加url参数
		if (params != null) {
			Iterator<String> it = params.keySet().iterator();
			StringBuffer sb = null;
			while (it.hasNext()) {
				String key = it.next();
				String value = params.get(key).toString();
				if (sb == null) {
					sb = new StringBuffer();
					sb.append("?");
				} else {
					sb.append("&");
				}
				try {
					sb.append(URLEncoder.encode(key, "UTF-8"));
					sb.append("=");
					sb.append(URLEncoder.encode(value, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			url += sb.toString();
		}
		return url;
	}
    private static NameValuePair basicNameValuePair(String name, String value) {
        return new BasicNameValuePair(name, value);
    }

	public static HttpEntity post(String url, Map<String, String> params) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
        httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        httpClient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        httpClient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
        HttpPost post = new HttpPost(url);
		if (params != null && !params.isEmpty()) {
			UrlEncodedFormEntity formEntity = null;
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			for (String paramName : params.keySet()) {
				postParams.add(HttpUtils.basicNameValuePair(paramName, params.get(paramName)));
			}
			try {
				formEntity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
                //formEntity.setContentType(HTTP.UTF_8);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

            post.setEntity(formEntity);
		}
		System.out.println("请求URL " + post.getURI());
		try {
			httpClient.execute(post);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

    public static String post2(String url1, String email) {
            try{
                URL url = new URL(url1);
                URLConnection connection = url.openConnection();
                /**
                 * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。
                 * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做：
                 */
                connection.setDoOutput(true);
                /**
                 * 最后，为了得到OutputStream，简单起见，把它约束在Writer并且放入POST信息中，例如： ...
                 */
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "8859_1");
                out.write("api_key=qNjl140ESQWl0MdCk2p8oA&api_secret=FJNHvGJHLinDsrx2RyfMj1BYJSVtyMJCLt08&type=1&email="+email+"&host_id=I-vsfuLMQJCGVlzLvQD1Aw"); //向页面传递数据。post的关键所在！

                out.flush();
                out.close();

                String sCurrentLine;
                String sTotalString;
                sCurrentLine = "";
                sTotalString = "";
                InputStream l_urlStream;
                l_urlStream = connection.getInputStream();
                // 传说中的三层包装阿！
                BufferedReader l_reader = new BufferedReader(new InputStreamReader(
                        l_urlStream));
                while ((sCurrentLine = l_reader.readLine()) != null) {
                    sTotalString += sCurrentLine ;

                }
                JSONObject jsonObject = JSONObject.fromObject(sTotalString);
                return (String)jsonObject.get("id");

            } catch (Exception e){
                e.printStackTrace();
            }
        return null;

    }
}
